package service

import (
	"gin-build/config"
	"gin-build/hanlder/model"
	"gin-build/hanlder/request"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.GetUserByUsername(config.DB, form.Username); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}
	if user.ID > 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "用户已存在",
		})
		return
	}
	user.Username = form.Username
	user.Password = form.Password
	if err := user.CreatUser(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func GetUser(c *gin.Context) {
	var form request.GetUser
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.GetUserId(config.DB, form.UserId); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	form.UserId = user.UserId
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
}
func UsernameList(c *gin.Context) {
	var req request.UsernameList
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	user, total, err := model.UsernameList(config.DB, req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "搜索失败",
			"err":  err.Error(),
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"data": map[string]interface{}{
			"user":  user,
			"total": total,
			"page":  req.Page,
			"size":  req.Size,
		},
	})
}
func AddFriend(c *gin.Context) {
	var form request.AddFriend
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var f model.Friend
	if f.IsFriend(config.DB, form.FriendID, form.UserID) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "好友已存在",
		})
		return
	}
	f.FriendId = form.FriendID
	f.UserId = form.UserID
	if err := f.AddFriend(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "添加好友失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加好友成功",
	})
}
